<template>
  <div class="app-container">
    <!-- 搜索栏 -->
    <div class="search-container">
      <el-form :inline="true" :model="searchParams" class="demo-form-inline">
        <el-form-item label="合同编号">
          <el-input v-model="searchParams.contractId" placeholder="请输入合同编号" clearable />
        </el-form-item>
        <el-form-item label="超市">
          <el-select v-model="searchParams.supermarketId" placeholder="请选择超市" clearable>
            <el-option v-for="item in supermarketList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="合同类型">
          <el-select v-model="searchParams.contractType" placeholder="请选择合同类型" clearable>
            <el-option :label="'返保'" :value="1" />
            <el-option :label="'年限'" :value="2" />
            <el-option :label="'租金'" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="是否到期">
          <el-select v-model="searchParams.isExpired" placeholder="请选择状态" clearable>
            <el-option :label="'未到期'" :value="0" />
            <el-option :label="'已到期'" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 工具栏 -->
    <div class="toolbar">
      <el-button type="primary" icon="el-icon-plus" @click="handleCreate">新增合同</el-button>
    </div>

    <!-- 表格 -->
    <el-table
      v-loading="listLoading"
      :data="contractList"
      border
      style="width: 100%"
    >
      <el-table-column prop="id" label="合同编号" width="180" align="center" />
      <el-table-column prop="supermarketName" label="超市名称" width="180" align="center" />
      <el-table-column prop="contractType" label="合同类型" width="120" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.contractType === 1">返保</span>
          <span v-else-if="scope.row.contractType === 2">年限</span>
          <span v-else-if="scope.row.contractType === 3">租金</span>
          <span v-else>未知</span>
        </template>
      </el-table-column>
      <el-table-column prop="startTime" label="开始时间" width="180" align="center" />
      <el-table-column prop="endTime" label="结束时间" width="180" align="center" />
      <el-table-column prop="isExpired" label="是否到期" width="100" align="center">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.isExpired" type="danger">已到期</el-tag>
          <el-tag v-else type="success">未到期</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createdAt" label="创建时间" width="180" align="center" />
      <el-table-column label="操作" width="150" align="center">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="danger" size="mini" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-show="total > 0"
        :current-page="pagination.currentPage"
        :page-size="pagination.pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 合同编辑对话框 -->
    <el-dialog
      :visible.sync="dialogVisible"
      :title="dialogTitle"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px">
        <el-form-item label="超市" prop="supermarketId">
          <el-select v-model="formData.supermarketId" placeholder="请选择超市" style="width: 100%">
            <el-option v-for="item in supermarketList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="合同类型" prop="contractType">
          <el-select v-model="formData.contractType" placeholder="请选择合同类型" style="width: 100%">
            <el-option :label="'返保'" :value="1" />
            <el-option :label="'年限'" :value="2" />
            <el-option :label="'租金'" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker v-model="formData.startTime" type="datetime" style="width: 100%" placeholder="请选择开始时间" />
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker v-model="formData.endTime" type="datetime" style="width: 100%" placeholder="请选择结束时间" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as contractApi from '@/api/warehouse/contract'
import { getSupermarketList } from '@/api/warehouse/supermarket'

export default {
  name: 'ContractManagement',
  data() {
    return {
      // 列表数据
      contractList: [],
      total: 0,
      listLoading: false,

      // 搜索参数
      searchParams: {
        contractId: 0,
        supermarketId: 0,
        contractType: 0,
        isExpired: -1, // -1: 所有, 0: 未到期, 1: 已到期
      },

      // 分页参数
      pagination: {
        currentPage: 1,
        pageSize: 10
      },

      // 超市列表
      supermarketList: [],

      // 对话框数据
      dialogVisible: false,
      dialogTitle: '新增合同',
      formData: {
        id: '',
        supermarketId: '',
        contractType: '',
        startTime: '',
        endTime: ''
      },

      // 表单验证规则
      formRules: {
        supermarketId: [
          { required: true, message: '请选择超市', trigger: 'change' }
        ],
        contractType: [
          { required: true, message: '请选择合同类型', trigger: 'change' }
        ],
        startTime: [
          { required: true, message: '请选择开始时间', trigger: 'change' }
        ],
        endTime: [
          { required: true, message: '请选择结束时间', trigger: 'change' },
          {
            validator: (rule, value, callback) => {
              if (value && this.formData.startTime) {
                if (new Date(value).getTime() <= new Date(this.formData.startTime).getTime()) {
                  callback(new Error('结束时间必须大于开始时间'))
                } else {
                  callback()
                }
              } else {
                callback()
              }
            },
            trigger: 'change'
          }
        ]
      }
    }
  },

  created() {
    this.initData()
  },

  methods: {
    // 初始化数据
    async initData() {
      await this.loadSupermarketList()
      this.getContractList()
    },

    // 加载超市列表
    async loadSupermarketList() {
      try {
        const res = await getSupermarketList({ pageSize: 1000 })
        if (res.code === 200) {
          this.supermarketList = res.data.list
        }
      } catch (error) {
        this.$message.error('获取超市列表失败')
      }
    },

    // 获取合同列表
    async getContractList() {
      this.listLoading = true
      try {
        const params = {
          ...this.searchParams,
          page: this.pagination.currentPage,
          pageSize: this.pagination.pageSize
        }
        const res = await contractApi.list(params)
        if (res.code === 200) {
          this.contractList = res.data.list
          this.total = res.data.total
        }
      } catch (error) {
        this.$message.error('获取合同列表失败')
      } finally {
        this.listLoading = false
      }
    },

    // 搜索
    handleSearch() {
      this.pagination.currentPage = 1
      this.getContractList()
    },

    // 重置搜索
    resetSearch() {
      this.searchParams = {
        contractId: '',
        supermarketId: '',
        contractType: '',
        isExpired: ''
      }
      this.pagination.currentPage = 1
      this.getContractList()
    },

    // 分页大小改变
    handleSizeChange(size) {
      this.pagination.pageSize = size
      this.getContractList()
    },

    // 当前页码改变
    handleCurrentChange(current) {
      this.pagination.currentPage = current
      this.getContractList()
    },

    // 新增合同
    handleCreate() {
      this.dialogTitle = '新增合同'
      this.formData = {
        id: '',
        supermarketId: '',
        contractType: '',
        startTime: '',
        endTime: ''
      }
      this.dialogVisible = true
    },

    // 编辑合同
    async handleEdit(row) {
      this.dialogTitle = '编辑合同'
      try {
        const res = await contractApi.get({ id: row.id })
        if (res.code === 200) {
          this.formData = { ...res.data }
          this.dialogVisible = true
        }
      } catch (error) {
        this.$message.error('获取合同详情失败')
      }
    },

    // 删除合同
    handleDelete(row) {
      this.$confirm(`确定要删除合同 ${row.id} 吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        try {
          const res = await contractApi.delete_({ id: row.id })
          if (res.code === 200) {
            this.$message.success('删除成功')
            this.getContractList()
          }
        } catch (error) {
          this.$message.error('删除失败')
        }
      })
    },

    // 提交表单
    async handleSubmit() {
      this.$refs.formRef.validate(async(valid) => {
        if (valid) {
          try {
            let res
            if (this.formData.id) {
              // 编辑
              res = await contractApi.update(this.formData)
            } else {
              // 新增
              res = await contractApi.create(this.formData)
            }

            if (res.code === 200) {
              this.$message.success(this.formData.id ? '更新成功' : '创建成功')
              this.dialogVisible = false
              this.getContractList()
            }
          } catch (error) {
            this.$message.error(this.formData.id ? '更新失败' : '创建失败')
          }
        }
      })
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.search-container {
  margin-bottom: 20px;
}

.toolbar {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
